package com.walle.ak47.commons.jaxrs.cxf.interceptor;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.XMLMessage;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.fusesource.hawtbuf.ByteArrayInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.walle.ak47.commons.redis.RedisContextHolder;
import com.walle.ak47.commons.utils.StringUtils;

public class StintIP extends AbstractPhaseInterceptor<XMLMessage> 
{
	@Autowired
	RedisContextHolder redisContextHolder ;
	
	private int cacheSeconds = 60*60*1000;
	
	private static final Logger LOG = LoggerFactory.getLogger(CheckHeader.class);

	public StintIP() {
		super(Phase.PRE_INVOKE);// 该拦截器在调用前拦截HttpHeader信息
	}

	@Override
	public void handleMessage(XMLMessage msg) throws Fault {
		 	
		HttpServletRequest request = (HttpServletRequest) msg.get(AbstractHTTPDestination.HTTP_REQUEST);
        String ipAddress="";
        if (null != request) {
            ipAddress = request.getRemoteAddr(); // 取客户端IP地址
            LOG.info("请求客户端的IP地址:" + ipAddress);
            if ( StringUtils.isNotBlank(ipAddress) && redisContextHolder.inrcMapValueToJedis( "StintIPs", ipAddress, 1, cacheSeconds) > 5 )
            {
            	try
            	{
	            	 
	            	msg.setContent( OutputStream.class, new ByteArrayInputStream("aa".getBytes()));
	//            	throw new Fault(new IllegalAccessException("IP受限制:"+ipAddress));
            	}
            	catch( Exception ex )
            	{
            		ex.printStackTrace(); 
            	}
            }
        }
        
	}

	@Override
	public void handleFault(XMLMessage message) {
		super.handleFault(message);
	}
	
	public RedisContextHolder getRedisContextHolder() {
		return redisContextHolder;
	}

	public void setRedisContextHolder(RedisContextHolder redisContextHolder) {
		this.redisContextHolder = redisContextHolder;
	}

	public int getCacheSeconds() {
		return cacheSeconds;
	}

	public void setCacheSeconds(int cacheSeconds) {
		this.cacheSeconds = cacheSeconds;
	}
 
}
